package com.cust.zy.newtask.activity;

import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.cust.zy.newtask.R;
import com.cust.zy.newtask.TaskApplication;
import com.cust.zy.newtask.model.Word;
import com.cust.zy.newtask.tools.TaskResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhuangyuan on 4/14/2017.
 * 邮箱：zhuangyuan.k@qq.com
 */

public class KillWordsActivity extends AppCompatActivity {
    public final static String TIME_MESSAGE = "TIME_MESSAGE";
    public final static String WORD_VIEW_DATA = "WORD_VIEW_DATA";
    public final static String AM_OR_PM = "AM_OR_PM";
    public final static String AM = "AM";
    public final static String PM = "PM";
    private final static String LOG = "KillWordsActivity";

    public final static int GAP_REVIEW_WORDS_ACTIVITY_REQUEST = 0;

    private int thirtyMPosition = 0;
    private int startPosition = 0;
    private int endPosition;
    private int minutes;

    private TextView timeText = null;
    private ListView wordList;
    ArrayList<Word> data = null;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            timeText.setText(bundle.getString(TIME_MESSAGE));
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kill_words);
        Bundle bundle = this.getIntent().getExtras();
        String amOrPm = bundle.getString(AM_OR_PM);
        data = new ArrayList<Word>();
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("干掉词汇");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        KillWordsActivity.this, R.style.ExitAlertDialogStyle);
                builder.setTitle("tip");
                builder.setMessage("是否要退出词汇页面？");
                builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int position) {
                        timer.cancel();
                        finish();
                    }
                });
                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int position) {
                        dialog.cancel();
                    }
                });
                builder.show();
            }
        });
        timeText = (TextView) findViewById(R.id.timeCount);
        timer.start();
        wordList = (ListView) this.findViewById(R.id.words);
        GetWordListTask getWordListTask = new GetWordListTask(amOrPm);
        getWordListTask.execute();
    }

    final CountDownTimer timer = new CountDownTimer(360000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            Message m = new Message();
            Bundle bundle = new Bundle();
            bundle.putString(TIME_MESSAGE, (millisUntilFinished / 60000)
                    + "分" + (millisUntilFinished / 1000) % 60 + "秒后进入单词复习");
            m.setData(bundle);
            handler.handleMessage(m);
        }

        @Override
        public void onFinish() {
            Message m = new Message();
            Bundle bundle = new Bundle();
            bundle.putString(TIME_MESSAGE, "时间到！");
            m.setData(bundle);
            handler.handleMessage(m);
            endPosition = wordList.getLastVisiblePosition();
            minutes += 5;

            Intent intent = new Intent(KillWordsActivity.this, GapReviewWordsActivity.class);
//          序列化Word,Activity之间传递ArrayList<Word>  start-end  添加生词本功能。
            List<Word> subList = data.subList(minutes%30==0? thirtyMPosition:startPosition,endPosition);
            ArrayList<Word> temp = new ArrayList<>();
            for(Word word : subList){
                temp.add(word);
            }
            intent.putParcelableArrayListExtra(WORD_VIEW_DATA,temp);
            startActivityForResult(intent,GAP_REVIEW_WORDS_ACTIVITY_REQUEST);
            temp.clear();
            if(minutes%30 == 0){
                thirtyMPosition = endPosition;
            }
            startPosition = endPosition;
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case GAP_REVIEW_WORDS_ACTIVITY_REQUEST:
                timer.start();
                break;
        }
    }

    private class GetWordListTask extends AsyncTask<String, Object, TaskResult<List<Map<String, Object>>>> {
        private String amOrPm;

        public GetWordListTask(String amOrPm) {
            this.amOrPm = amOrPm;
        }

        @Override
        protected TaskResult<List<Map<String, Object>>> doInBackground(String... arg0) {
            try {
                TaskApplication taskApplication = (TaskApplication) getApplication();
                List<List<Word>> wordListData = null;
                if (amOrPm.equals(AM)) {
                    wordListData = taskApplication.getAmMap();
                } else if (amOrPm.equals(PM)) {
                    wordListData = taskApplication.getPmMap();
                }
                List<Map<String, Object>> listData = new ArrayList<Map<String, Object>>();
                int index = 0;
                for(List<Word> list:wordListData){
                    for (Word word : list) {
                        data.add(word);
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put(TaskApplication.TASK_ID_STRING, word.getTaskID());
                        map.put("word_name", word.getName());
                        map.put("word_soundMark", "[......]");
                        map.put("word_order", ++index + "/" + word.getList());
                        map.put("word_translation", word.getTranslation());
                        map.put("word_list", word.getList());
                        listData.add(map);
                    }
                }
                return new TaskResult<List<Map<String, Object>>>(listData);
            } catch (Exception e) {
                return new TaskResult<List<Map<String, Object>>>(e);
            }
        }

        @Override
        protected void onPostExecute(TaskResult<List<Map<String, Object>>> result) {
            if (result.isValid()) {
                SimpleAdapter adapter = new SimpleAdapter(KillWordsActivity.this, result.getResult(), R.layout.item_word_list,
                        new String[]{"word_name", "word_soundMark", "word_order", "word_translation"},
                        new int[]{R.id.word_name, R.id.word_soundMark, R.id.word_order, R.id.word_translation});
                wordList.setAdapter(adapter);
                //为了配合有道词典、Google翻译的复制查词功能
                wordList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                        ListView list = (ListView)parent;
                        Map<String, Object> map = (Map<String, Object>) list.getItemAtPosition(position);
                        String wordName = (String) map.get("word_name");
                        ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                        cm.setText(wordName);
                        return true;
                    }
                });
            } else {
                Log.e(LOG, result.getException().toString());
            }
        }
    }
}
